﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.IO;

namespace FusionDotNet
{
    /// <summary>
    /// Deletes rows from a Google Fusion Table.
    /// </summary>
    public class DeleteCommand : PostCommand<CommandResult>
    {
        /// <summary>
        /// Default Constructor.
        /// </summary>
        /// <param name="rowData">DataRow that identifies the rows to delete.</param>
        /// <remarks>
        /// The DataRow must have a column named 'rowid' with a value that represents a row in the database. The DataTable to which the DataRow is attached may not be null and must specify a DataTable Name.
        /// </remarks>
        public DeleteCommand(DataRow rowData)
        {
            BuildDeleteString(rowData);
        }

        private void BuildDeleteString(DataRow rowData)
        {
            rowData.Table
                .TableNotNull()
                .TableHasName()
                .TableHasRowIdColumn();

            StringBuilder builder = new StringBuilder();
            builder.Append("sql=");
            builder.AppendFormat("DELETE FROM {0} WHERE ROWID = '{1}'", rowData.Table.TableName, rowData[Constants.FUSION_ROWID]);

            Encoding encoding = GetContentEncoding();
            PostContent = encoding.GetBytes(builder.ToString());
        }

        /// <summary>
        /// Creates a CommandResult based on the results of the command. 
        /// </summary>
        /// <param name="reader">StreamReader containing the results of the operation.</param>
        /// <returns><see cref="CommandResult"/></returns>
        internal override CommandResult CreateResult(System.IO.StreamReader reader)
        {
            string status = reader.ReadLine();
            var result = new CommandResult();
            if (status == Constants.STATUS_OK)
            {

                result.Success = true;
            }
            else
            {
                result.Success = false;
            }
            return result;
        }

    }
}
